import { h, mergeProps, onUnmounted, ref, watch } from 'vue';
import { Input } from 'ant-design-vue';

export default {
  name: 'CInput',
  props: {
    modelValue: String,
    max: Number,
  },
  emits: ['update:modelValue', 'change'],
  setup(props, { attrs, emit }) {
    let str = ref('');

    function onChange(e) {
      let val = e.target.value;
      if (props.max > 0) {
        val = val.substr(0, props.max);
      }
      str.value = val;
      emit('update:modelValue', str.value);
      emit('change', str.value);
    }

    watch(
      () => props.modelValue,
      (value) => {
        if (typeof value === 'string' && value !== str.value) {
          str.value = value;
        }
      },
      { immediate: true },
    );

    onUnmounted(() => {
      props = attrs = str = null;
    });

    return () =>
      h(Input, mergeProps({}, attrs, { value: str.value, style: { width: '100%' }, onChange }), {
        suffix: () => {
          return props.max > 0 ? h('span', { style: { opacity: 0.3 } }, str.value.length + '/' + props.max) : null;
        },
      });
  },
};
